// tiktok_hook.js (Enumerate Exports and Hook)
Java.perform(function() {
    console.log("Enumerating module exports and hooking potential network functions...");

    const networkFunctions = [
        "socket", "connect", "send", "recv", "read", "write",
        "sendto", "recvfrom", "bind", "listen", "accept", "close"
    ];

    // Helper function to parse sockaddr_in structure (from previous script)
    function SocketAddress(address, len) {
        this.ipAddress = "";
        this.port = 0;

        if (len >= 16) { // sockaddr_in6
            this.ipAddress = address.add(8).readUtf8String(16); // Placeholder
            this.port = address.add(2).readU16();
        } else if (len >= 8) { // sockaddr_in
            this.ipAddress = address.add(4).readUtf8String(4).split('').map(function(c) {
                return c.charCodeAt(0);
            }).join('.');
            this.port = address.add(2).readU16();
        }
    }

    // Enumerate all loaded modules
    Process.enumerateModules().forEach(function(module) {
        // Filter out system libraries that are less likely to contain custom network code
        // Focus on app's own libraries or known network libraries
        if (module.path.includes("com.zhiliaoapp.musically") || module.path.includes("libokhttp") || module.path.includes("libttnet")) { // Add other relevant library names if known
            console.log(`\n[+] Scanning module: ${module.name} (${module.path})`);

            // Enumerate exports for the current module
            module.enumerateExports().forEach(function(exp) {
                // Check if the export name matches any of our target network functions
                if (networkFunctions.includes(exp.name)) {
                    try {
                        console.log(`  |-- Found potential network function: ${exp.name} at ${exp.address}`);

                        // Attach Interceptor to the found function
                        Interceptor.attach(exp.address, {
                            onEnter: function(args) {
                                console.log(`    [Hook] ${exp.name}() called in ${module.name}`);
                                // Log arguments based on function name
                                if (exp.name === "connect") {
                                    const socket = args[0].toInt32();
                                    const addr = args[1];
                                    const addrlen = args[2].toInt32();
                                    const sockaddr_in = new SocketAddress(addr, addrlen);
                                    console.log(`      Socket: ${socket}, Address: ${sockaddr_in.ipAddress}:${sockaddr_in.port}`);
                                } else if (exp.name === "send" || exp.name === "write") {
                                    const buf = args[1];
                                    const len = args[2].toInt32();
                                    console.log(`      Data (hex): ${hexdump(buf, { length: Math.min(len, 64) })}`);
                                    console.log(`      Data (UTF-8): ${buf.readUtf8String(Math.min(len, 64))}`);
                                } else if (exp.name === "recv" || exp.name === "read") {
                                    // For recv/read, data is available on onLeave
                                }
                            },
                            onLeave: function(retval) {
                                if (exp.name === "recv" || exp.name === "read") {
                                    if (retval.toInt32() > 0) {
                                        const buf = this.context.x1; // Assuming x1 holds the buffer on ARM64
                                        console.log(`      Received ${retval.toInt32()} bytes`);
                                        console.log(`      Data (hex): ${hexdump(buf, { length: Math.min(retval.toInt32(), 64) })}`);
                                        console.log(`      Data (UTF-8): ${buf.readUtf8String(Math.min(retval.toInt32(), 64))}`);
                                    }
                                }
                            }
                        });
                    } catch (e) {
                        console.error(`    [Error] Failed to attach to ${exp.name} in ${module.name}: ${e.message}`);
                    }
                }
            });
        }
    });

    console.log("Module export enumeration and hooking complete.");
});